<?php
namespace Cmf\Forms;

use Cmf\Models\Menu;
use Cmf\Models\Tree;

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Submit;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Forms\Element\Select;
use Phalcon\Validation\Validator\PresenceOf;

/**
 * 菜单表单
 */
class MenuForm extends Form
{
	public function initialize($menu,$action = null)
	{
		$title = new Text('title',[
			'required'                => 'required',
			'placeholder'             => '请输入菜单标题',
			'data-validation-message' => '菜单标题不能为空',
		]);
		$title->setLabel('菜单标题');
		$title->addValidators([new PresenceOf(['message' => '菜单不能为空'])]);
		$this->add($title);

		$url = new Text('url',[
			'required'                => 'required',
			'placeholder'             => '请输入菜单链接',
			'data-validation-message' => '菜单链接不能为空',
		]);
		$url->setLabel('菜单链接');
		$url->addValidators([new PresenceOf(['message' => '菜单链接不能为空'])]);
		$this->add($url);

		$sort = new Text('sort',[
			'value'                   => 0,
			'required'                => 'required',
			'placeholder'             => '请输入菜单排序',
			'data-validation-message' => '菜单排序不能为空',
		]);
		$sort->setLabel('菜单排序');
		$this->add($sort);


		$option = menu::find();
		$tree = tree::toFormatTree($option->toArray());
		$option = array();
		$option[0] = '/';
		foreach($tree as $key => $value) {
			$option[$value['id']] = $value['title_show'];
		}
		$pid = new Select('pid',
			$option,
			['data-am-selected' => "{btnSize: 'xm',btnWidth: '100%'}"]
		);
		$pid->setLabel('父级菜单');
		$this->add($pid);

		$is_group = new Select('is_group',
			['0' => '否','1' => '是'],
			['data-am-selected' => "{btnSize: 'xm',btnWidth: '100%'}"]);
		$is_group->setLabel('分组菜单');
		$this->add($is_group);

		$is_hide = new Select('is_hide',
			['1' => '是','0' => '否'],
			['data-am-selected' => "{btnSize: 'xm',btnWidth: '100%'}"]);
		$is_hide->setLabel('是否隐藏');
		$this->add($is_hide);

		$this->add(new Submit('submit',['class' => 'am-btn am-btn-primary','value' => '保存修改']));
		$this->add(new Hidden('status',['value' => 1]));

		if(!empty($menu) && $action === 'edit') {
			$id = new Hidden('id');
			$this->add($id);
		}
	}

	public function renderDecorated($name)
	{
		$element = $this->get($name);
		$messages = $this->getMessagesFor($element->getName());

		if(!in_array($element->getName(),['id','role_id'])) {
			$input = '<div class="am-form-group">';
			$input .= '<label for="'.$element->getName().'" class="am-u-sm-3 am-form-label">'
				.$element->getLabel()
				.'</label>'
				.'<div class="am-u-sm-9">'
				.$element
				.'</div>';

			if(count($messages)) {
				$input .= '<div class="am-alert-flash am-u-sm-9">';
				foreach($messages as $message) {
					$input .= $this->flash->error($message);
				}
				$input .= '</div>';
			}
			$input .= '</div>';
		} else {
			$input = $element;
		}

		echo $input;
	}
}
